# -*- coding: utf-8 -*-
"""A Namespace describes a QPBuild Namespace. These entities are created by
polling the namespace server(s) and merging the results into the database.
"""

from sqlalchemy import *
from sqlalchemy.orm import mapper, relation
from sqlalchemy import Table, ForeignKey, Column
from sqlalchemy.types import Integer, Unicode
#from sqlalchemy.orm import relation, backref

from abserver.model import DeclarativeBase, metadata, DBSession


# Namespaces. Updated by consulting the namespace server
class Namespace(DeclarativeBase):
    # table options
    __tablename__ = 'namespace'

    # columns
    namespace_id = Column(Integer, primary_key=True, autoincrement=True)
    namespace_name = Column(Unicode(64), unique=True, nullable=False)
    namespace_sccs_server = Column(Unicode(256))
    namespace_description = Column(Unicode(2042))

    # relationships
    #components

    def __init__(self, namespace_name, namespace_sccs_server=None, namespace_description=None):
        self.namespace_name = namespace_name
        self.namespace_sccs_server = namespace_sccs_server
        self.namespace_description = namespace_description
        
    @classmethod
    def get_namespace(cls, namespace, namespace_sccs_server="", namespace_description=""):
        ns = DBSession.query(cls).filter(cls.namespace_name==namespace).first()
        if not ns:
            # create a new namespace object
            ns = cls(namespace, namespace_sccs_server, namespace_description)
            print dir(ns)
            DBSession.add(ns)
            print "CREATED", namespace
        else:
            print "GOT NAMESPACE", ns.namespace_name
        return ns

